<template>
  <view class="container">
    <!-- 收货地址 -->
    <view class="address-section" @click="selectAddress">
      <view v-if="selectedAddress" class="address-info">
        <view class="address-header">
          <text class="name">{{ selectedAddress.recipientName }}</text>
          <text class="phone">{{ selectedAddress.recipientPhone }}</text>
        </view>
        <view class="address-detail">
          {{ formatAddress(selectedAddress) }}
        </view>
      </view>
      <view v-else class="no-address">
        <text class="add-address-text">添加收货地址</text>
      </view>
      <text class="address-arrow">></text>
    </view>

    <!-- 商品列表 -->
    <view class="order-items">
      <view class="section-title">商品清单</view>
      <view class="item-list">
        <view v-for="(item, index) in orderItems" :key="index" class="order-item">
          <image :src="item.product.image || '/static/images/default-category.png'" class="item-image" mode="aspectFill"></image>
          <view class="item-info">
            <text class="item-name">{{ item.product.name }}</text>
            <text class="item-specs">{{ formatSpecs(item.sku) }}</text>
            <view class="item-price-qty">
              <text class="item-price">¥{{ formatPrice(item.sku.price) }}</text>
              <text class="item-qty">x{{ item.quantity }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 配送方式 -->
    <view class="delivery-section">
      <view class="section-title">配送方式</view>
      <view class="delivery-options">
        <view 
          v-for="(option, index) in deliveryOptions" 
          :key="index" 
          class="delivery-option"
          :class="{ active: selectedDelivery === option.value }"
          @click="selectDelivery(option.value)"
        >
          <text class="option-name">{{ option.name }}</text>
          <text class="option-fee">{{ option.fee > 0 ? `¥${formatPrice(option.fee)}` : '免费' }}</text>
        </view>
      </view>
      
      <!-- 自提门店信息 -->
      <view v-if="selectedDelivery === 'self'" class="store-info">
        <view class="store-title">自提门店</view>
        <view class="store-detail">
          <text class="store-name">{{ currentStoreName || '请在首页选择门店' }}</text>
        </view>
      </view>
    </view>

    <!-- 优惠券 -->
    <view class="coupon-section" @click="selectCoupon">
      <text class="section-title">优惠券</text>
      <view class="coupon-info">
        <text v-if="selectedCoupon" class="coupon-name">
          {{ selectedCoupon.name }} - 
          <text v-if="selectedCoupon.type === 'amount'">¥{{ formatPrice(selectedCoupon.amount) }}</text>
          <text v-else-if="selectedCoupon.type === 'percentage'">{{ (selectedCoupon.amount * 10).toFixed(1) }}折</text>
        </text>
        <text v-else class="no-coupon">{{ availableCoupons.length > 0 ? `有${availableCoupons.length}张可用优惠券` : '无可用优惠券' }}</text>
        <text class="coupon-arrow">></text>
      </view>
    </view>

    <!-- 订单备注 -->
    <view class="remark-section">
      <text class="section-title">订单备注</text>
      <input 
        class="remark-input" 
        type="text" 
        placeholder="选填，请填写其他需求" 
        v-model="remark"
        maxlength="100"
      />
    </view>

    <!-- 配送备注 - 新增 -->
    <view class="remark-section" v-if="selectedDelivery === 'local'">
      <text class="section-title">配送备注</text>
      <input 
        class="remark-input" 
        type="text" 
        placeholder="选填，请填写配送特殊需求（如：放门口，不要辣等）" 
        v-model="deliveryNotes"
        maxlength="100"
      />
    </view>

    <!-- 订单金额 -->
    <view class="price-section">
      <view class="price-item">
        <text class="price-label">商品金额</text>
        <text class="price-value">¥{{ formatPrice(goodsAmount) }}</text>
      </view>
      <view class="price-item">
        <text class="price-label">运费</text>
        <text class="price-value">¥{{ formatPrice(deliveryFee) }}</text>
      </view>
      <view class="price-item" v-if="discountAmount > 0">
        <text class="price-label">优惠券</text>
        <text class="price-value">-¥{{ formatPrice(discountAmount) }}</text>
      </view>
      <view class="price-item total">
        <text class="price-label">应付金额</text>
        <text class="price-value total-amount">¥{{ formatPrice(totalAmount) }}</text>
      </view>
    </view>

    <!-- 提交订单 -->
    <view class="submit-section">
      <view class="total-info">
        <text class="total-label">合计：</text>
        <text class="total-price">¥{{ formatPrice(totalAmount) }}</text>
      </view>
      <button class="submit-btn" @click="submitOrder" :disabled="!canSubmit || submitting">
        {{ submitting ? '提交中...' : '提交订单' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onLoad} from '@dcloudio/uni-app';
import { previewOrderFromCart, previewOrderFromProduct, createOrder } from '../../api/order.js';
import storage from '@/utils/storage.js';
import mapService from '@/utils/mapService.js';

// 页面参数
const cartItemIds = ref('');
const productId = ref(null);
const skuId = ref(null);
const quantity = ref(null);

// 订单数据
const orderItems = ref([]);
const selectedAddress = ref(null);
const selectedDelivery = ref('local');
const selectedCoupon = ref(null);
const availableCoupons = ref([]);
const remark = ref('');
const deliveryNotes = ref('');
const loading = ref(false);
const submitting = ref(false);
const goodsAmount = ref(0);
const deliveryFee = ref(0);
const discountAmount = ref(0);

// 门店信息
const currentStoreId = ref(null);
const currentStoreName = ref('');

// 配送方式选项
const deliveryOptions = [
  { name: '同城配送', value: 'local', fee: 3.00 },
  { name: '到店自提', value: 'self', fee: 0.00 },
];

// 格式化价格
const formatPrice = (price) => {
  if (price === undefined || price === null) return '0.00';
  
  // 如果是字符串，尝试转换为数字
  let numPrice = typeof price === 'string' ? parseFloat(price) : Number(price);
  
  // 检查是否为有效数字
  if (isNaN(numPrice)) return '0.00';
  
  // 判断单位：如果是整数且大于100，可能是"分"为单位，转换为"元"
  // 或者如果是小数但值很大（如888.00），也可能是"分"为单位
  if ((Number.isInteger(numPrice) && numPrice > 100) || 
      (!Number.isInteger(numPrice) && numPrice > 100 && numPrice % 1 === 0)) {
    numPrice = numPrice / 100;
  }
  
  // 格式化为2位小数
  return numPrice.toFixed(2);
};

// 格式化规格
const formatSpecs = (sku) => {
  if (!sku || !sku.specs) return '默认规格';
  try {
    if (typeof sku.specs === 'string') {
		// 检查是否已经是中文规格描述字符串（不是JSON格式）
		if (/^[\u4e00-\u9fa5]/.test(sku.specs) || !sku.specs.startsWith('{')) {
			// 如果是中文字符开头或不是以{开头，直接返回原字符串
			return sku.specs;
		}
      const specs = JSON.parse(sku.specs);
      return Object.values(specs).join(' / ');
    }
    return Object.values(sku.specs).join(' / ');
  } catch (e) {
    console.error('规格解析错误:', e);
    return sku.specs || '默认规格';
  }
};

// 格式化地址
const formatAddress = (address) => {
  if (!address) return '';
  const province = address.province || '';
  const city = address.city || '';
  const district = address.district || '';
  const detail = address.detailAddress || '';
  
  // 避免null值
  return `${province || ''}${city || ''}${district || ''}${detail || ''}`;
};

// 格式化日期，兼容iOS
const formatDateString = (dateStr) => {
  if (!dateStr) return '';
  
  try {
    // 手动解析日期字符串，避免使用可能在iOS上不兼容的日期格式
    // 处理格式如: "2023-06-30T12:00:00" 或 "2023-06-30 12:00:00"
    const regex = /(\d{4})[/-](\d{1,2})[/-](\d{1,2})(?:[T ](\d{1,2}):(\d{1,2}):(\d{1,2}))?/;
    const match = dateStr.match(regex);
    
    if (match) {
      const year = parseInt(match[1]);
      const month = parseInt(match[2]);
      const day = parseInt(match[3]);
      
      // 返回 yyyy/MM/dd 格式 (iOS兼容格式)
      return `${year}/${month.toString().padStart(2, '0')}/${day.toString().padStart(2, '0')}`;
    }
    
    // 如果无法解析，返回原始字符串的前10个字符
    return dateStr.substring(0, 10).replace(/-/g, '/');
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateStr;
  }
};

// 计算总金额
const totalAmount = computed(() => {
  return goodsAmount.value + deliveryFee.value - discountAmount.value;
});

// 是否可以提交订单
const canSubmit = computed(() => {
  return orderItems.value.length > 0 && selectedAddress.value !== null;
});

// 选择收货地址
const selectAddress = () => {
  uni.navigateTo({
    url: '/pages/address/list?select=true',
    events: {
      // 监听地址选择事件
      addressSelected: (address) => {
        console.log('接收到选择的地址:', address);
        selectedAddress.value = address;
      }
    },
    success: (res) => {
      // 添加全局事件监听作为备用方案
      const eventChannel = res.eventChannel;
      
      // 监听全局事件
      const addressSelectedHandler = (address) => {
        console.log('通过全局事件接收到地址:', address);
        selectedAddress.value = address;
        // 使用完毕后移除监听
        uni.$off('addressSelected', addressSelectedHandler);
      };
      
      uni.$on('addressSelected', addressSelectedHandler);
    }
  });
};

// 选择配送方式
const selectDelivery = (value) => {
  selectedDelivery.value = value;
  
  // 更新配送费
  const option = deliveryOptions.find(opt => opt.value === value);
  if (option) {
    deliveryFee.value = option.fee;
  }
};

// 选择优惠券
const selectCoupon = () => {
  if (availableCoupons.value.length === 0) {
    uni.showToast({
      title: '暂无可用优惠券',
      icon: 'none'
    });
    return;
  }

  // 构建优惠券显示项
  const couponItems = availableCoupons.value.map(coupon => {
    let description = '';
    if (coupon.minAmount > 0) {
      description = `满${formatPrice(coupon.minAmount)}元可用`;
    }
    if (coupon.startTime && coupon.endTime) {
      // 使用兼容iOS的日期格式化函数
      const start = formatDateString(coupon.startTime);
      const end = formatDateString(coupon.endTime);
      description += description ? `，${start}至${end}` : `${start}至${end}`;
    }
    
    // 根据优惠券类型显示不同的名称
    let couponName = '';
    if (coupon.type === 'amount') {
      // 固定金额优惠券
      couponName = `${coupon.name} - ¥${formatPrice(coupon.amount)}`;
    } else if (coupon.type === 'percentage') {
      // 折扣优惠券，例如0.88表示88折
      const discountPercent = (coupon.amount * 10).toFixed(1);
      couponName = `${coupon.name} - ${discountPercent}折`;
    } else {
      couponName = coupon.name;
    }
    
    return {
      name: couponName,
      description: description || '无使用限制'
    };
  });

  // 显示优惠券列表底部弹窗
  uni.showActionSheet({
    itemList: couponItems.map(item => item.name),
    success: function (res) {
      selectedCoupon.value = availableCoupons.value[res.tapIndex];
      
      // 根据优惠券类型计算优惠金额
      if (selectedCoupon.value.type === 'amount') {
        // 固定金额优惠
        discountAmount.value = selectedCoupon.value.amount;
      } else if (selectedCoupon.value.type === 'percentage') {
        // 折扣优惠
        // 计算折扣金额：商品总金额 * (1 - 折扣率)
        discountAmount.value = goodsAmount.value * (1 - selectedCoupon.value.amount);
      }
      
      // 显示优惠券详情
      uni.showToast({
        title: couponItems[res.tapIndex].description,
        icon: 'none',
        duration: 2000
      });
    }
  });
};

// 检查配送距离是否超过限制
const checkDeliveryDistance = () => {
  // 如果选择的是自提，不需要检查距离
  if (selectedDelivery.value === 'self') {
    return true;
  }
  
  // 如果没有地址或没有经纬度，无法检查距离
  if (!selectedAddress.value || !selectedAddress.value.latitude || !selectedAddress.value.longitude) {
    return true;
  }
  
  // 店铺位置（固定为南宁市中心坐标）
  const storeLocation = {
    latitude: 22.817, 
    longitude: 108.366
  };
  
  // 用户地址位置
  const userLocation = {
    latitude: selectedAddress.value.latitude,
    longitude: selectedAddress.value.longitude
  };
  
  // 计算距离（米）
  const distance = mapService.calculateDistance(userLocation, storeLocation);
  
  // 最大配送距离（15公里）
  const MAX_DELIVERY_DISTANCE = 15000;
  
  if (distance > MAX_DELIVERY_DISTANCE) {
    uni.showModal({
      title: '超出配送范围',
      content: `您的收货地址距离店铺${mapService.formatDistance(distance)}，超出了最大配送范围（15公里），请更换地址或选择自提。`,
      showCancel: false
    });
    return false;
  }
  
  return true;
};

// 加载订单预览数据
const loadOrderPreview = async () => {
  try {
    loading.value = true;
    let res;
    
    if (cartItemIds.value) {
      // 从购物车创建订单
      res = await previewOrderFromCart(cartItemIds.value);
    } else if (productId.value && skuId.value && quantity.value) {
      // 直接购买
      res = await previewOrderFromProduct(productId.value, skuId.value, quantity.value);
    } else {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }
    
    if (res.code === 200 && res.data) {
      // 设置订单预览数据
      orderItems.value = res.data.items || [];
      goodsAmount.value = res.data.goodsAmount || 0;
      deliveryFee.value = res.data.deliveryFee || 0;
      
      
      // 检查价格类型和格式
      if (orderItems.value.length > 0) {
        const firstItem = orderItems.value[0];
      }
      
      // 设置可用优惠券
      availableCoupons.value = res.data.availableCoupons || [];
      
      // 如果有默认地址，设置默认地址
      if (res.data.address) {
        selectedAddress.value = res.data.address;
      } else {
        // 如果没有地址，提示用户添加地址
        uni.showToast({
          title: '请添加收货地址',
          icon: 'none'
        });
      }
    } else {
      uni.showToast({
        title: res.msg || '获取订单预览失败',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  } catch (error) {
    console.error('获取订单预览失败:', error);
    uni.showToast({
      title: '获取订单预览失败，请稍后再试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    uni.hideLoading();
  }
};

// 提交订单
const submitOrder = async () => {
  if (submitting.value) return;
  
  if (!selectedAddress.value && selectedDelivery.value === 'local') {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none'
    });
    return;
  }

  if (selectedDelivery.value === 'self' && !currentStoreId.value) {
    uni.showToast({
      title: '请先选择自提门店',
      icon: 'none'
    });
    return;
  }

  // 检查配送距离
  if (!checkDeliveryDistance()) {
    return;
  }

  submitting.value = true;
  
  try {
    // 构建提交数据
    const orderData = {
      cartItemIds: cartItemIds.value || '',
      productId: productId.value || null,
      skuId: skuId.value || null,
      quantity: quantity.value || null,
      addressId: selectedAddress.value ? selectedAddress.value.id : null,
      deliveryType: selectedDelivery.value,
      couponId: selectedCoupon.value ? selectedCoupon.value.id : null,
      remark: remark.value,
      storeId: currentStoreId.value,
      deliveryNotes: deliveryNotes.value // 添加配送备注
    };
    
    console.log('提交订单数据:', orderData);
    
    const result = await createOrder(orderData);
    console.log('订单创建结果:', result);
    
    if (result && result.data && result.data.id) {
      // 订单创建成功，跳转到支付页面
      uni.navigateTo({
        url: `/pages/payment/index?orderId=${result.data.id}&amount=${totalAmount.value}`
      });
    } else {
      uni.showToast({
        title: '订单创建失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('订单创建异常:', error);
    uni.showToast({
      title: error.message || '订单创建失败',
      icon: 'none'
    });
  } finally {
    submitting.value = false;
  }
};

// 页面加载
onLoad((options) => {
  if (options.cart_item_ids) {
    cartItemIds.value = options.cart_item_ids;
  } else if (options.product_id && options.sku_id && options.quantity) {
    productId.value = parseInt(options.product_id);
    skuId.value = parseInt(options.sku_id);
    quantity.value = parseInt(options.quantity);
  } else {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
  
  // 获取当前选择的门店信息
  currentStoreId.value = storage.getCurrentStoreId();
  currentStoreName.value = storage.getCurrentStoreName();
  
  if (!currentStoreId.value) {
    uni.showToast({
      title: '请先在首页选择门店',
      icon: 'none'
    });
  }
});

// 页面加载时获取订单预览数据
onMounted(() => {
  uni.showLoading({
    title: '加载中...'
  });
  loadOrderPreview();
});

// 页面卸载时清除可能的全局事件监听
onUnmounted(() => {
  uni.$off('addressSelected');
});
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.address-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  position: relative;
}

.address-info {
  flex: 1;
}

.address-header {
  display: flex;
  margin-bottom: 10rpx;
}

.name {
  font-size: 32rpx;
  font-weight: bold;
  margin-right: 20rpx;
}

.phone {
  font-size: 28rpx;
  color: #666;
}

.address-detail {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

.no-address {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
}

.add-address-text {
  font-size: 28rpx;
  color: #ff6700;
}

.address-arrow {
  font-size: 32rpx;
  color: #999;
  margin-left: 20rpx;
}

.order-items {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.item-list {
  border-radius: 12rpx;
  overflow: hidden;
}

.order-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 140rpx;
  height: 140rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 28rpx;
  line-height: 1.4;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.item-specs {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.item-price-qty {
  display: flex;
  justify-content: space-between;
}

.item-price {
  font-size: 28rpx;
  color: #ff6700;
  font-weight: bold;
}

.item-qty {
  font-size: 26rpx;
  color: #666;
}

.delivery-section, .coupon-section, .remark-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.delivery-options {
  display: flex;
  flex-wrap: wrap;
}

.delivery-option {
  width: 220rpx;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.delivery-option.active {
  border-color: #ff6700;
  background-color: #fff7f5;
}

.option-name {
  font-size: 26rpx;
  color: #333;
}

.option-fee {
  font-size: 22rpx;
  color: #999;
  margin-top: 5rpx;
}

.coupon-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-name {
  font-size: 28rpx;
  color: #ff6700;
}

.no-coupon {
  font-size: 28rpx;
  color: #999;
}

.coupon-arrow {
  font-size: 32rpx;
  color: #999;
}

.remark-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  margin-top: 20rpx;
}

.price-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.price-item:last-child {
  margin-bottom: 0;
}

.price-label {
  font-size: 28rpx;
  color: #333;
}

.price-value {
  font-size: 28rpx;
  color: #333;
}

.price-item.total {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.total-amount {
  font-size: 32rpx;
  color: #ff6700;
  font-weight: bold;
}

.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.total-info {
  flex: 1;
}

.total-label {
  font-size: 26rpx;
  color: #333;
}

.total-price {
  font-size: 32rpx;
  color: #ff6700;
  font-weight: bold;
}

.submit-btn {
  width: 220rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #ff6700;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  margin-left: 20rpx;
}

.submit-btn[disabled] {
  background-color: #ccc;
}

.store-info {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 8rpx;
  border: 1rpx solid #ddd;
}

.store-title {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.store-detail {
  font-size: 26rpx;
  color: #666;
}
</style> 